var fs = require('fs');
var express = require('express');
var multer = require('multer');
var path = require('path');
var router = express.Router();
var bodyParser = require('body-parser')
// 引入 express-jwt 和 jsonwebtoken
const expressJwt = require('express-jwt');
const jwt = require('jsonwebtoken');

// 设置 JWT 密钥
const secretKey = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyIjoiYWRtaW4iLCJpYXQiOjE3Mjg1NjA3MjIsImV4cCI6MTcyODU2NDMyMn0.kFFse-q2Pc5fQUM6Av3Ov5N34znGSY-D2NF5HZG8MB0eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyIjoiYWRtaW4iLCJpYXQiOjE3Mjg1NjA3MjMsImV4cCI6MTcyODU2NDMyM30.thjeNORVTDD-l3oa67TmY8-ahrTi_W4vQhwM8j161Bg'
// 添加 JWT 中间件，保护除 / 和 /safety 以外的接口
router.use(expressJwt({ secret: secretKey }).unless({ path: ['/', '/favicon.ico','/safety', '/getFileList', '/getFileOrganization', '/clearEmptyFolders', '/static/jquery.js', '/download', '/handleFile', '/filelist', '/static/font/OPPOSans-B-2.ttf'] }));

// 安全访问接口
router.post('/safety', (req, res) => {
    // 生成 JWT token
    const token = jwt.sign({ user: 'admin' }, secretKey, { expiresIn: '1h' });
    // 将 token 存储到浏览器存储（例如 localStorage 或 sessionStorage）
    // console.log(token);
    res.json({ token });
    // res.cookie('token', token, { httpOnly: true }); 
    // res.send('Token generated successfully');
});

// 自定义错误处理中间件，处理 JWT 验证失败
router.use((err, req, res, next) => {
    if (err.name === 'UnauthorizedError') {
        res.status(401).send('未通过安全检查'); // 返回 401 未授权
    } else {
        next(err);
    }
});

//创建application/x-www-form-urlencoded
var urlencodedParser = bodyParser.urlencoded({ extended: false });

// 更改大文件的存储路径
var createFolder = function (folder) {
    try {
        fs.accessSync(folder);
    } catch (e) {
        fs.mkdirSync(folder);
    }
};

var uploadFolder = './upload/';// 设定存储文件夹为当前目录下的 /upload 文件夹
createFolder(uploadFolder);
// 磁盘存贮
var storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, uploadFolder); // 他会放在当前目录下的 /upload 文件夹下（没有该文件夹，就新建一个）
    },
    filename: function (req, file, cb) { // 在这里设定文件名
        cb(null, file.originalname);
    }
})

var upload = multer({ storage: storage })

//创建application/json解析
router.use(bodyParser.json());

// 上传页面
router.get('/', (req, res) => {
    console.log(__dirname)
    res.sendFile(path.join(__dirname, '../views/upload.html'))
})

// 列表页面
router.get('/filelist', function (req, res) {
    res.sendFile(path.join(__dirname, '../views/filelist.html'))
})

//分组页面
router.get('/handleFile', function (req, res) {
    res.sendFile(path.join(__dirname, '../views/handleFile.html'))
})
//判断进程
router.post('/stats', expressJwt({ secret: secretKey }), (req, res) => {
    var SS = true;
    res.json({ SS });
});
// 上传文件
router.post('/upload', expressJwt({ secret: secretKey }), upload.array('file'), function (req, res) {
    console.dir(req.files)

    if (!req.files || Object.keys(req.files).length === 0) {
        res.status(400).send('请选择要上传的文件！');
        return;
    }

    // 重定向到列表页
    res.redirect('/filelist')
});

// 下载文件
router.get('/download', function (req, res) {
    var filePath = req.query.path;
    filePath = path.join(__dirname, '../' + filePath);//本地调试
    // filePath = '/root/' + filePath;//服务器目录
    console.log('下载文件：' + filePath)
    res.attachment(filePath)
    res.sendFile(filePath)
})

// 删除文件
router.post('/delete', expressJwt({ secret: secretKey }), function (req, res, next) {
    var filePath = req.body.filePath;
    console.log('删除文件：' + filePath)

    try {
        fs.unlinkSync(filePath)
        // 重定向到列表页
        res.send('删除成功')
    } catch (error) {
        res.send('删除失败')
    }

})
// 移出文件
router.post('/moveout', expressJwt({ secret: secretKey }), function (req, res, next) {
    var filePath = req.body.filePath;
    let path = filePath;
    let newPath = path.replace(/\/.*?\//, "/");
    // console.log('old文件：' + filePath);
    console.log('new文件path：' + newPath);

    try {
        // fs.unlinkSync(filePath)
        fs.rename(filePath, newPath, err => { })
        // 重定向到列表页
        res.send('移出成功')
    } catch (error) {
        res.send('移出失败')
    }
})
// 移动文件
router.post('/movein', expressJwt({ secret: secretKey }), function (req, res, next) {
    var filePath = req.body.filePath;
    var dirPath = req.body.dirPath;
    console.log('文件：' + filePath + "目录：" + dirPath);
    try {
        // fs.unlinkSync(filePath)
        fs.rename(filePath, dirPath, err => { })
        // 重定向到列表页
        res.send('移出成功')
    } catch (error) {
        res.send('移出失败')
    }
})
// 处理清除空文件夹
router.get('/clearEmptyFolders', (req, res) => {
    const uploadDir = uploadFolder;
    // 读取upload目录下的所有子目录
    fs.readdir(uploadDir, (err, files) => {
        if (err) {
            console.error(err);
            res.status(500).send('Error reading directory');
            return;
        }

        files.forEach((file) => {
            const subDir = path.join(uploadDir, file);
            // 判断是否是文件夹并且是否为空
            fs.stat(subDir, (err, stat) => {
                if (err) {
                    console.error(err);
                    return;
                }
                if (stat.isDirectory() && fs.readdirSync(subDir).length === 0) {
                    // 如果是空文件夹则删除
                    fs.rmdir(subDir, (err) => {
                        if (err) {
                            console.error(err);
                        }
                    });
                }
            });
        });
    });
});
// 迁移文件的接口
router.post('/migrateFiles', expressJwt({ secret: secretKey }), (req, res) => {
    const subDirName = req.body.dirName;
    console.log(subDirName + "这是要解散的目录");
    if (!req.body.dirName) { return; }
    const uploadDir = uploadFolder;
    const sourceDir = path.join(uploadDir, subDirName);

    // 检查源目录是否存在
    if (!fs.existsSync(sourceDir)) {
        res.status(404).send('Source directory does not exist');
        return;
    }

    // 读取源目录下的文件
    fs.readdir(sourceDir, (err, files) => {
        if (err) {
            console.error(err);
            res.status(500).send('Error reading source directory');
            return;
        }

        files.forEach((file) => {
            const sourceFile = path.join(sourceDir, file);
            const destFile = path.join(uploadDir, file);
            fs.rename(sourceFile, destFile, (err) => {
                if (err) {
                    console.error(err);
                }
            });
        });

        res.send('Files migrated successfully');
    });
});
// 创建目录接口
router.post('/createDirectory', expressJwt({ secret: secretKey }), async (req, res) => {
    console.log("这b函数已经调用了");

    // console.log(JSON.stringify(req.query) + req.body + "这是穿来的值");
    console.log(req.body);

    if (!req.body) {
        return res.status(400).json({ message: '缺少目录名' });
    }

    var directoryName = req.body.directoryName;
    var fullPath = path.resolve(uploadFolder, directoryName); // 使用绝对路径

    try {
        console.log('创建目录的完整路径：', fullPath);
        await fs.promises.mkdir(fullPath, { recursive: true });
        res.json({ message: '创建目录成功' });
    } catch (err) {
        console.error('创建目录失败：', err);
        // 根据错误类型返回不同的错误信息
        if (err.code === 'EACCES') {
            res.status(500).json({ message: '权限不足，无法创建目录' });
        } else if (err.code === 'ENOSPC') {
            res.status(500).json({ message: '磁盘空间不足' });
        } else {
            res.status(500).json({ message: '创建目录失败', error: err.message });
        }
    }
});

// 获取文件列表
router.get('/getFileList', function (req, res, next) {
    var filelist = getFileList('upload')
    res.send(filelist)
})

// 获取文件统计信息
router.get('/getFileOrganization', function (req, res, next) {
    var filelist = getFileList('upload');
    var folderCounts = {};

    filelist.forEach(file => {
        folderCounts[file.folder] = (folderCounts[file.folder] || 0) + 1;
    });

    // 将 folderCounts 转换为 chartData 格式
    const chartData = Object.keys(folderCounts).map(folder => ({
        value: folderCounts[folder],
        name: folder
    }));

    res.send(chartData);
});

function getFileList(path) {
    var filelist = [];
    readFile(path, filelist);

    return filelist;
}


function readFile(path, filelist) {
    var files = fs.readdirSync(path);
    files.forEach(walk);

    function walk(file) {
        var state = fs.statSync(path + '/' + file)
        if (state.isDirectory()) {
            readFile(path + '/' + file, filelist)
        } else {
            var obj = new Object;
            obj.size = state.size;
            obj.name = file;
            obj.path = path + '/' + file;
            obj.folder = path;
            if (obj.folder.includes('upload')) {
                obj.folder = obj.folder.replace('upload', '');
                if (obj.folder.trim() === '') {
                    obj.folder = 'root';
                } else {
                    obj.folder = obj.folder.replace('/', '');
                }
            };
            filelist.push(obj);
        }
    }
}
module.exports = router;